<template>
  <el-dialog
    v-el-drag-dialog
    title="新增"
    :visible.sync="visible"
    width="700px"
    @closed="reset"
  >
    <el-form ref="dataForm" :rules="rules" :model="form" label-position="right" label-width="100px">
      <el-form-item label="商品分类" prop="gtypeId">
        <el-select v-model="form.gtypeId" placeholder="请选择" @change="chooseType">
          <el-option
            v-for="item in typeList"
            :key="item.gtId"
            :label="item.gtName"
            :value="item.gtId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商品名称" prop="goodsId">
        <el-select v-model="form.goodsId" placeholder="请选择" clearable>
          <el-option
            v-for="item in goodsList"
            :key="item.goodsId"
            :label="item.goodsName"
            :value="item.goodsId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="批量设置" :table-form-merge="2" prop="date">
        <el-date-picker
          v-model="form.date"
          type="daterange"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :clearable="true"
          value-format="yyyy-MM-dd"
        />
      </el-form-item>
      <el-form-item class="countGroup" label="" prop="radioType" label-width="40px">
        <el-radio-group v-model="form.radioType">
          <el-radio :label="1">全时段数量:
            <el-input v-model.number="form.total" style="width: 200px; vertical-align: middle;" oninput="value=value.replace(/[^\d]/g,'')" :max="399" :min="0">
              <template slot="append">瓶</template>
            </el-input>
          </el-radio>
          <el-radio :label="2" style="margin-top: 15px;">分时段数量:
            <div class="timeCount">
              <el-input v-for="(item,index) in timePeriod" :key="index" v-model.number="form['num'+index]" oninput="value=value.replace(/[^\d]/g,'')" :max="399" :min="0">
                <template slot="prepend">{{ item.start+'~'+item.end }}</template>
                <template slot="append">瓶</template>
              </el-input>
            </div>

          </el-radio>
        </el-radio-group>

      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="reset">
        取消
      </el-button>
      <el-button :loading="$loadingPlugin.toSave" type="primary" @click="add">
        确定
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
  import { goodsTypeQueryAllList, querySpecList, saveOrderSetting } from '@/api'
  export default {
    name: '',
    props: {
      parentFetchData: {
        type: Function
      },
      timePeriod: {
        type: Array,
        default: () => []
      }
    },
    data() {
      return {
        visible: false,
        form: {
          gtypeId: null,
          goodsId: null,
          date: [],
          total: null
        },
        typeList: [],
        goodsList: [],
        rules: {
          gtypeId: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
          goodsId: [{ required: true, message: '请选择商品', trigger: 'change' }],
          date: [{ required: true, message: '请选择批量设置时间', trigger: 'change' }],
          radioType: [{ required: true, message: '请选择全时段/分时段模式', trigger: 'change' }]
        }
      }
    },
    created() {
      this.getMap()
    },
    methods: {
      // 获取商品分类枚举
      async getMap() {
        const res = await goodsTypeQueryAllList()
        this.typeList = res.data || []
      },
      // 选择商品分类
      async chooseType(value) {
        this.goodsList = []
        this.form.goodsId = null
        const res = await querySpecList({ currentPage: 1, pageSize: 999, gtId: value })
        this.goodsList = res.data.rows || []
      },
      open(temp) {
        this.temp = temp
        return new Promise(resolve => {
          this.visible = true
        })
      },
      add() {
        // 分时段
        let totalStr = ''
        if (this.form.radioType === 2) {
          const str = []
          for (const item in this.form) {
            if (item.indexOf('num') > -1) {
              const index = item.split('m')[1]
              str[index] = this.form[item]
            }
          }
          totalStr = str.join(',')
        }
        this.$refs.dataForm.validate(valid => {
          if (!valid) return
          const params = {
            orgId: this.temp.orgId,
            gtypeId: this.form.gtypeId,
            goodsId: this.form.goodsId,
            startTime: this.form.date[0],
            doneTime: this.form.date[1],
            total: this.form.total,
            timeStr: this.timePeriod.map((item) => (item.start + '-' + item.end)).join(';'),
            totalDay: this.dateDiff('D', new Date(this.form.date[0] + ' 00:00:00'), new Date(this.form.date[1] + ' 00:00:00')),
            radioType: this.form.radioType,
            totalStr: totalStr
          }
          this.toSave(params)
        })
      },
      async toSave(params) {
        // console.log(params)
        const res = await saveOrderSetting(params)
        if (res) {
          this.$notify({
            title: '提示',
            message: '设置成功',
            type: 'success',
            duration: 2000
          })
          this.$emit('updateList', this.temp)
          this.visible = false
        }
      },
      reset() {
        this.form = {
          gtypeId: null,
          goodsId: null,
          date: [],
          total: null
        }
        this.$nextTick(() => {
          this.$refs.dataForm.clearValidate()
        })
        this.visible = false
      },
      dateDiff(interval, dt1, dt2) {
        if (!dt1) {
          dt1 = new Date()
        }
        if (!dt2) {
          dt2 = new Date()
        }
        if (arguments.length < 2) {
          return 0
        }
        var objInterval = {
          'D': 1000 * 60 * 60 * 24,
          'H': 1000 * 60 * 60,
          'M': 1000 * 60,
          'S': 1000,
          'T': 1
        }
        interval = interval.toUpperCase()
        // return Math.round((dt2.getTime() - dt1.getTime()) / eval('objInterval.' + interval))
        return Math.round((dt2.getTime() - dt1.getTime()) / objInterval[interval])
      }
    }
  }
</script>

<style lang="scss" scoped>
.timeCount {
  margin-top: 10px;
  white-space: break-spaces;
  /deep/.el-input {
    width: 270px;
    margin-right: 10px;
    margin-bottom: 10px;
  }
}
.countGroup {
  /deep/ .el-form-item__content {
    margin-left: 36px !important;
  }
}

</style>
